<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            height: 100px;
            width: 40px;
            background-color: pink;
            top: 400px;
            left: 1360px;
        }
        .goBack{
            display: none;
            margin-top: 60px;
        }
        .w {
            /* position: abs; */
            width: 1200px;
            margin: 0 auto;
            margin-top: 10px;
        }
        .header {
            background-color: purple;
            height: 150px;
            /* margin-top: 10px; */
        }
        .banner {
            background-color: skyblue;
            height: 330px;
        }
        .main {
            background-color: red;
            height: 2000px;
            /* margin-top: 10px; */
        }
    </style>
</head>
<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header w">头部区域</div>
    <div class="banner w">banner区域</div>
    <div class="main w">主题区域</div>
    <script>
        var sliderbar = document.querySelector('.slider-bar');
        var bannde = document.querySelector('.banner');
        var bannerTop = bannde.offsetTop;
        var sloderbarTop = sliderbar.offsetTop - bannerTop;
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        document.addEventListener('scroll',function(){
            // console.log(window.pageYOffset);
            // console.log(bannerTop);
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sloderbarTop + 'px';
            }else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top =' 400px';

            }
            if(window.pageYOffset >= mainTop){
                goBack.style.display = 'block';
            }else {
                goBack.style.display = 'none';
            }
        })
        goBack.addEventListener('click',function(){
            animate(window,0);
        });
        //动画函数
        function animate(obj,target,callback){
        clearInterval(obj.timer);
        obj.timer = setInterval(function(){
        var step =(target - window.pageYOffset )/10;
        step = step > 0? Math.ceil(step):Math.floor(step);
        if(window.pageYOffset == target){
            //清楚定时器
            clearInterval(obj.timer);
            if (callback) {
                callback();
            }
        }
        window.scroll(0,window.pageYOffset + step)
    },15)
    }
    </script>
</body>
</html>